package com.fortune.app.models;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

/**
 * 周易八卦算法实现类
 */
public class ZhouYiDivination {
    private Map<String, String> baguaNames;
    private Map<String, int[]> baguaYao;
    private Map<String, String> baguaElements;
    private Map<String, Map<String, String>> hexagrams;
    
    public ZhouYiDivination() {
        initBaguaData();
        initHexagrams();
    }
    
    /**
     * 初始化八卦数据
     */
    private void initBaguaData() {
        // 八卦名称
        baguaNames = new HashMap<>();
        baguaNames.put("111", "乾");
        baguaNames.put("110", "兑");
        baguaNames.put("101", "离");
        baguaNames.put("100", "震");
        baguaNames.put("011", "巽");
        baguaNames.put("010", "坎");
        baguaNames.put("001", "艮");
        baguaNames.put("000", "坤");
        
        // 八卦对应的三爻组合（从下到上）
        baguaYao = new HashMap<>();
        baguaYao.put("乾", new int[]{1, 1, 1});
        baguaYao.put("兑", new int[]{1, 1, 0});
        baguaYao.put("离", new int[]{1, 0, 1});
        baguaYao.put("震", new int[]{0, 0, 1});
        baguaYao.put("巽", new int[]{1, 1, 0});
        baguaYao.put("坎", new int[]{0, 1, 0});
        baguaYao.put("艮", new int[]{1, 0, 0});
        baguaYao.put("坤", new int[]{0, 0, 0});
        
        // 八卦五行属性
        baguaElements = new HashMap<>();
        baguaElements.put("乾", "金");
        baguaElements.put("兑", "金");
        baguaElements.put("离", "火");
        baguaElements.put("震", "木");
        baguaElements.put("巽", "木");
        baguaElements.put("坎", "水");
        baguaElements.put("艮", "土");
        baguaElements.put("坤", "土");
    }
    
    /**
     * 初始化六十四卦数据
     */
    private void initHexagrams() {
        hexagrams = new HashMap<>();
        
        // 这里只列出部分示例，实际实现需要完整的六十四卦数据
        Map<String, String> qian = new HashMap<>();
        qian.put("name", "乾为天");
        qian.put("description", "大吉大利，刚健自强，充满活力。");
        qian.put("career", "事业蒸蒸日上，适合开拓进取。");
        qian.put("love", "感情稳定，但需注意过于刚强可能引起矛盾。");
        qian.put("health", "精力充沛，但需注意休息，避免过度劳累。");
        qian.put("fortune", "财运亨通，适合投资与拓展。");
        hexagrams.put("111111", qian);
        
        Map<String, String> kun = new HashMap<>();
        kun.put("name", "坤为地");
        kun.put("description", "柔顺包容，厚德载物，利于安守本分。");
        kun.put("career", "稳步发展，适合脚踏实地工作。");
        kun.put("love", "感情温和，包容与理解是关键。");
        kun.put("health", "身体状况平稳，注意休养生息。");
        kun.put("fortune", "财运稳定，适合储蓄与稳健投资。");
        hexagrams.put("000000", kun);
        
        // 其他卦象数据...
    }
    
    /**
     * 生成卦象
     * 
     * @param birthDate 用户生日，格式为"YYYY-MM-DD"
     * @param currentTime 当前时间，格式为"YYYY-MM-DD HH:MM:SS"
     * @param questionType 问题类型，如"事业"、"爱情"、"健康"等
     * @return 卦象结果
     */
    public Map<String, Object> castHexagram(String birthDate, String currentTime, String questionType) {
        try {
            // 解析生日和当前时间
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
            
            Date birthDt = dateFormat.parse(birthDate);
            Date currentDt = timeFormat.parse(currentTime);
            
            // 计算年龄
            Calendar birthCal = Calendar.getInstance();
            Calendar currentCal = Calendar.getInstance();
            birthCal.setTime(birthDt);
            currentCal.setTime(currentDt);
            
            int age = currentCal.get(Calendar.YEAR) - birthCal.get(Calendar.YEAR);
            if (currentCal.get(Calendar.MONTH) < birthCal.get(Calendar.MONTH) || 
                (currentCal.get(Calendar.MONTH) == birthCal.get(Calendar.MONTH) && 
                 currentCal.get(Calendar.DAY_OF_MONTH) < birthCal.get(Calendar.DAY_OF_MONTH))) {
                age--;
            }
            
            // 计算生肖
            String[] chineseZodiac = {"鼠", "牛", "虎", "兔", "龙", "蛇", "马", "羊", "猴", "鸡", "狗", "猪"};
            int zodiacIndex = (birthCal.get(Calendar.YEAR) - 4) % 12;
            String zodiac = chineseZodiac[zodiacIndex];
            
            // 生成随机种子
            int seed = birthCal.get(Calendar.YEAR) + birthCal.get(Calendar.MONTH) + birthCal.get(Calendar.DAY_OF_MONTH) +
                       currentCal.get(Calendar.YEAR) + currentCal.get(Calendar.MONTH) + currentCal.get(Calendar.DAY_OF_MONTH) +
                       currentCal.get(Calendar.HOUR_OF_DAY) + currentCal.get(Calendar.MINUTE) + currentCal.get(Calendar.SECOND) +
                       questionType.length() + age;
            
            Random random = new Random(seed);
            
            // 生成六爻
            int[] yao = new int[6];
            List<Integer> changingYao = new ArrayList<>();
            
            for (int i = 0; i < 6; i++) {
                // 模拟传统的掷钱币方式
                int[] coins = new int[3];
                for (int j = 0; j < 3; j++) {
                    coins[j] = random.nextInt(2) == 0 ? 2 : 3; // 2=反面，3=正面
                }
                int coinSum = coins[0] + coins[1] + coins[2];
                
                if (coinSum == 6) {  // 老阳，阳爻有变化
                    yao[i] = 1;
                    changingYao.add(i);
                } else if (coinSum == 7) {  // 少阳，阳爻无变化
                    yao[i] = 1;
                } else if (coinSum == 8) {  // 少阴，阴爻无变化
                    yao[i] = 0;
                } else if (coinSum == 9) {  // 老阴，阴爻有变化
                    yao[i] = 0;
                    changingYao.add(i);
                }
            }
            
            // 生成本卦
            StringBuilder originalHexagram = new StringBuilder();
            for (int i = 0; i < 6; i++) {
                originalHexagram.append(yao[i]);
            }
            
            // 生成变卦
            int[] changedYao = yao.clone();
            for (int i : changingYao) {
                changedYao[i] = 1 - changedYao[i];  // 0变1，1变0
            }
            
            StringBuilder changedHexagram = new StringBuilder();
            for (int i = 0; i < 6; i++) {
                changedHexagram.append(changedYao[i]);
            }
            
            // 获取上下卦
            String upperTrigram = originalHexagram.substring(3, 6);
            String lowerTrigram = originalHexagram.substring(0, 3);
            
            // 查找卦象解释
            Map<String, String> hexagramInfo = hexagrams.get(originalHexagram.toString());
            if (hexagramInfo == null) {
                hexagramInfo = new HashMap<>();
                hexagramInfo.put("name", "未知卦象");
                hexagramInfo.put("description", "请查阅详细的周易资料。");
                hexagramInfo.put("career", "暂无解析");
                hexagramInfo.put("love", "暂无解析");
                hexagramInfo.put("health", "暂无解析");
                hexagramInfo.put("fortune", "暂无解析");
            }
            
            // 根据问题类型提供针对性解释
            String specificAdvice = hexagramInfo.get(questionType.toLowerCase());
            if (specificAdvice == null) {
                specificAdvice = "请参考卦象总体解释";
            }
            
            // 计算吉凶指数
            List<String> luckyElements = new ArrayList<>();
            if (questionType.equals("事业")) {
                luckyElements.add("木");
                luckyElements.add("火");
            } else if (questionType.equals("爱情")) {
                luckyElements.add("金");
                luckyElements.add("水");
            } else {
                luckyElements.add("土");
            }
            
            String upperElement = baguaElements.get(trigramToBagua(upperTrigram));
            String lowerElement = baguaElements.get(trigramToBagua(lowerTrigram));
            
            int luckScore = 0;
            if (luckyElements.contains(upperElement)) {
                luckScore += 2;
            }
            if (luckyElements.contains(lowerElement)) {
                luckScore += 2;
            }
            luckScore += changingYao.size();  // 变爻越多，变化越大
            
            // 归一化到1-5分
            luckScore = Math.max(1, Math.min(5, luckScore));
            
            // 返回结果
            Map<String, Object> result = new HashMap<>();
            
            Map<String, Object> originalHexagramMap = new HashMap<>();
            originalHexagramMap.put("code", originalHexagram.toString());
            originalHexagramMap.put("name", hexagramInfo.get("name"));
            originalHexagramMap.put("description", hexagramInfo.get("description"));
            result.put("original_hexagram", originalHexagramMap);
            
            if (!changingYao.isEmpty()) {
                Map<String, Object> changedHexagramMap = new HashMap<>();
                changedHexagramMap.put("code", changedHexagram.toString());
                
                Map<String, String> changedHexagramInfo = hexagrams.get(changedHexagram.toString());
                changedHexagramMap.put("name", changedHexagramInfo != null ? changedHexagramInfo.get("name") : "未知变卦");
                
                result.put("changed_hexagram", changedHexagramMap);
            } else {
                result.put("changed_hexagram", null);
            }
            
            result.put("changing_yao", changingYao);
            result.put("upper_trigram", trigramToBagua(upperTrigram));
            result.put("lower_trigram", trigramToBagua(lowerTrigram));
            result.put("question_type", questionType);
            result.put("specific_advice", specificAdvice);
            result.put("luck_score", luckScore);
            
            Map<String, Object> userInfo = new HashMap<>();
            userInfo.put("age", age);
            userInfo.put("zodiac", zodiac);
            result.put("user_info", userInfo);
            
            result.put("divination_time", currentTime);
            
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }
    
    /**
     * 将三爻代码转换为八卦名称
     */
    private String trigramToBagua(String trigram) {
        return baguaNames.getOrDefault(trigram, "未知卦");
    }
}
